package com.fly.show.api;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

import javax.validation.Valid;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.fly.show.model.JsonResult;
import com.fly.show.model.User;
import com.fly.show.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * RestUserController
 * 
 * @author 00fly
 * @version [版本号, 2018-11-06]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@CrossOrigin
@Api(tags = "用户操作接口-api")
@RestController
@RequestMapping("/rest/user")
public class RestUserController
{
    @Autowired
    private IUserService userService;
    
    @ApiOperation("查看提交用户")
    @JsonView(User.All.class)
    @PostMapping("/submit")
    public JsonResult<User> show(@Valid @RequestBody User user)
    {
        return JsonResult.success(user);
    }
    
    @ApiOperation("查询用户摘要信息")
    @JsonView(User.Simple.class)
    @GetMapping("/simple")
    public List<User> simple()
    {
        return userService.list();
    }
    
    @ApiOperation("查询用户全部信息")
    @JsonView(User.All.class)
    @GetMapping("/all")
    public List<User> all()
    {
        return userService.list();
    }
    
    @ApiOperation("aop1查询用户全部信息")
    @GetMapping("/to/all")
    public Object toAll()
    {
        return userService.list();
    }
    
    @ApiOperation("aop2查询用户全部信息")
    @GetMapping("/json/all")
    public JsonResult<?> jsonAll()
    {
        return JsonResult.success(userService.list());
    }
    
    /**
     * unless 设置缓存不生效条件
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("缓存测试")
    @Cacheable(value = "users", key = "'cache'", unless = "#result['data'].size()==10")
    @GetMapping("/cache")
    public JsonResult<List<String>> cache()
    {
        log.info("new data run ......");
        List<String> data = new ArrayList<>();
        IntStream.range(0, 10).forEach(i -> data.add(RandomStringUtils.randomAlphabetic(8)));
        return JsonResult.success(data);
    }
}